/**
 * Hot Topic Panel Component
 * 热点话题面板组件，用于展示和选择热点进行创作
 */
import React, { useState, useEffect } from 'react';
import { Card, Tabs, List, Button, Tag, Space, Spin, message, Badge } from 'antd';
import { FireOutlined, RiseOutlined, CommentOutlined, EyeOutlined } from '@ant-design/icons';
import { hotRadarService } from '../../../services/hotRadar.service';
import { generationService } from '../../../services/generation.service';
import { useConversationStore } from '../../../stores/conversation.store';
import HotTopicCard from './HotTopicCard';
import CommentView from './CommentView';
import styles from './style.module.css';

const { TabPane } = Tabs;

interface HotTopic {
  id: string;
  title: string;
  excerpt: string;
  platform: string;
  rank: number;
  hot_value: number;
  url: string;
  comments?: Comment[];
  created_at: string;
}

interface Comment {
  content: string;
  author: string;
  likes: number;
  sentiment?: string;
}

const PLATFORMS = [
  { key: 'weibo', label: '微博', icon: '🔥' },
  { key: 'zhihu', label: '知乎', icon: '💡' },
  { key: 'toutiao', label: '头条', icon: '📰' },
  { key: 'douyin', label: '抖音', icon: '🎵' },
  { key: 'xiaohongshu', label: '小红书', icon: '📖' },
];

const HotTopicPanel: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('weibo');
  const [hotTopics, setHotTopics] = useState<HotTopic[]>([]);
  const [selectedTopic, setSelectedTopic] = useState<HotTopic | null>(null);
  const [showComments, setShowComments] = useState(false);
  
  const { setHotTopicContext, startNewConversation } = useConversationStore();

  // 获取热点数据
  const fetchHotTopics = async (platform: string) => {
    setLoading(true);
    try {
      const data = await hotRadarService.getLatestHotData(platform);
      setHotTopics(data.items || []);
    } catch (error) {
      console.error('Failed to fetch hot topics:', error);
      message.error('获取热点数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchHotTopics(activeTab);
  }, [activeTab]);

  // 基于热点开始创作
  const handleStartWriting = async (topic: HotTopic) => {
    try {
      setLoading(true);
      
      // 生成智能提示词
      const promptData = await generationService.generateHotTopicPrompt({
        title: topic.title,
        excerpt: topic.excerpt,
        platform: topic.platform
      });

      // 设置热点上下文
      setHotTopicContext({
        platform: topic.platform,
        topicId: topic.id,
        title: topic.title,
        excerpt: topic.excerpt,
        comments: topic.comments || [],
        perspectives: [],
        generatedPrompt: promptData.prompt
      });

      // 开始新对话
      await startNewConversation(promptData.prompt);
      
      message.success('已基于热点生成创作提示');
    } catch (error) {
      console.error('Failed to start writing:', error);
      message.error('生成创作提示失败');
    } finally {
      setLoading(false);
    }
  };

  // 查看评论
  const handleViewComments = (topic: HotTopic) => {
    setSelectedTopic(topic);
    setShowComments(true);
  };

  // 批量分析热点
  const handleBatchAnalysis = async () => {
    if (hotTopics.length === 0) {
      message.warning('没有可分析的热点');
      return;
    }

    try {
      setLoading(true);
      
      // 获取前3个热点进行综合分析
      const topTopics = hotTopics.slice(0, 3);
      const combinedPrompt = await generationService.generateCombinedPrompt(topTopics);
      
      // 设置综合热点上下文
      setHotTopicContext({
        platform: 'multi',
        topicId: 'combined',
        title: '综合热点分析',
        excerpt: topTopics.map(t => t.title).join('、'),
        comments: [],
        perspectives: [],
        generatedPrompt: combinedPrompt
      });

      await startNewConversation(combinedPrompt);
      message.success('已生成综合热点分析');
    } catch (error) {
      console.error('Failed to batch analyze:', error);
      message.error('批量分析失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <Card 
        title={
          <Space>
            <FireOutlined style={{ color: '#ff4d4f' }} />
            热点快速创作
          </Space>
        }
        extra={
          <Button 
            type="primary" 
            onClick={handleBatchAnalysis}
            disabled={hotTopics.length === 0}
          >
            综合分析Top3
          </Button>
        }
      >
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          tabBarStyle={{ marginBottom: 16 }}
        >
          {PLATFORMS.map(platform => (
            <TabPane 
              tab={
                <Space>
                  <span>{platform.icon}</span>
                  <span>{platform.label}</span>
                </Space>
              } 
              key={platform.key}
            >
              <Spin spinning={loading}>
                <List
                  grid={{ gutter: 16, column: 2 }}
                  dataSource={hotTopics}
                  renderItem={(topic, index) => (
                    <List.Item>
                      <HotTopicCard
                        rank={index + 1}
                        title={topic.title}
                        excerpt={topic.excerpt}
                        hotValue={topic.hot_value}
                        commentCount={topic.comments?.length || 0}
                        onStartWriting={() => handleStartWriting(topic)}
                        onViewComments={() => handleViewComments(topic)}
                      />
                    </List.Item>
                  )}
                />
              </Spin>
            </TabPane>
          ))}
        </Tabs>
      </Card>

      {/* 评论查看器 */}
      {showComments && selectedTopic && (
        <CommentView
          visible={showComments}
          topic={selectedTopic}
          onClose={() => {
            setShowComments(false);
            setSelectedTopic(null);
          }}
          onUseComments={async (comments) => {
            // 处理选中的评论
            const processedComments = await generationService.analyzeComments({
              comments,
              topic_keywords: [selectedTopic.title]
            });
            
            message.success(`已选择${comments.length}条高质量评论用于创作`);
            setShowComments(false);
          }}
        />
      )}
    </div>
  );
};

export default HotTopicPanel;